<template>
    <view class="media-detail-page">
        <u-loading-page :loading="loading"></u-loading-page>
        
        <!-- 导航栏 -->
        <u-navbar :title="navTitle" :placeholder="true" back-text="">
            <view class="u-nav-slot" slot="left" @click="$returnPage()">
                <u-icon name="arrow-left" size="20" color="#333"></u-icon>
            </view>
        </u-navbar>

        <!-- 主要内容区域 -->
        <view class="main-content" v-if="!loading">
            <!-- 上半部分：轮播第一个图片 -->
            <view class="top-section">
                <view class="first-media-container">
                    <!-- 如果第一个是图片或者第二个是图片 -->
                    <image 
                        v-if="firstMedia && firstMedia.type === 'image'"
                        :src="firstMedia.url" 
                        mode="aspectFill"
                        class="first-media-image"
                        @click="previewFirstMedia"
                    ></image>
                    
                    <!-- 如果第一个是视频且没有第二个媒体，或者第二个也是视频 -->
                    <view v-else-if="firstMedia && firstMedia.type === 'video'" class="first-video-wrapper">
                        <video 
                            :src="firstMedia.url"
                            :poster="firstMedia.poster || ''"
                            class="first-media-video"
                            :controls="true"
                            @click="playFirstVideo"
                        ></video>
                        <view class="video-play-overlay" @click="playFirstVideo">
                            <u-icon name="play-circle-fill" size="60" color="rgba(255,255,255,0.8)"></u-icon>
                        </view>
                    </view>
                    
                    <!-- 如果没有合适的媒体内容 -->
                    <view v-else class="no-media-placeholder">
                        <u-icon name="camera" size="60" color="#ccc"></u-icon>
                        <text class="placeholder-text">暂无媒体内容</text>
                    </view>
                    
                    <!-- 媒体信息标签 -->
                    <view class="media-info-badge">
                        <u-icon 
                            :name="firstMedia && firstMedia.type === 'video' ? 'play-circle' : 'camera'" 
                            size="16" 
                            color="#fff"
                        ></u-icon>
                        <text class="media-count-text">{{ mediaList.length }}</text>
                    </view>
                </view>
            </view>

            <!-- 下半部分：背景图和左右按钮 -->
            <view class="bottom-section">
                <!-- 背景容器 -->
                <view class="background-container">
                    <!-- 背景图片 -->
                    <image 
                        src="http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/9ffbe93b-2fba-4114-9159-2c605420d6fb.jpg?Expires=4911628355&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=%2FWShu5E7K5ts4MqgSNcB%2BAuw%2Bn0%3D"
                        mode="aspectFill"
                        class="background-image"
                    ></image>
                    
                    <!-- 内容覆盖层 -->
                    <view class="content-overlay">
                        <!-- 左侧按钮 -->
                        <view class="action-button left-button" @click="onLeftButtonClick">
                        </view>
                        
                        <!-- 右侧按钮 -->
                        <view class="action-button right-button" @click="onRightButtonClick">
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 空状态 -->
        <view v-if="!loading && mediaList.length === 0" class="empty-state">
            <u-empty 
                mode="data" 
                icon="/static/empty_list.png" 
                text="暂无媒体内容"
            ></u-empty>
        </view>
        
        <!-- 写信模态框 -->
        <view v-if="showWriteModal" class="modal-overlay" @click="closeWriteModal">
            <view class="modal-container" @click.stop>
                <view class="modal-header">
                    <text class="modal-title">写一封信</text>
                    <view class="modal-close" @click="closeWriteModal">
                        <u-icon name="close" size="20" color="#666"></u-icon>
                    </view>
                </view>
                
                <view class="modal-content">
                    <view class="write-letter-content">
                        <view class="letter-tips">
                            <text class="tips-text">博物馆倡导发布健康的内容，对色情擦边违法等内容零容忍。如若发现违规，将计入黑名单并依法处理，感谢您的理解。</text>
                        </view>
                        <textarea 
                            v-model="writeContent"
                            placeholder="请输入你想说的话..."
                            class="letter-textarea"
                            maxlength="500"
                            :show-confirm-bar="false"
                        ></textarea>
                        <view class="word-count">
                            <text class="count-text">{{ writeContent.length }}/500</text>
                        </view>
                    </view>
                </view>
                
                <view class="modal-footer">
                    <view class="modal-button cancel-button" @click="closeWriteModal">
                        <text class="button-text">取消</text>
                    </view>
                    <view class="modal-button confirm-button" @click="submitLetter">
                        <text class="button-text">投递</text>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 读信模态框 -->
        <view v-if="showReadModal" class="modal-overlay" @click="closeReadModal">
            <view class="modal-container" @click.stop>
                <view class="modal-header">
                    <text class="modal-title">捡到一封信</text>
                    <view class="modal-close" @click="closeReadModal">
                        <u-icon name="close" size="20" color="#666"></u-icon>
                    </view>
                </view>
                
                <view class="modal-content">
                    <view class="read-letter-content" v-if="currentLetter">
                        <view class="letter-header">
                            <text class="letter-author">来自：{{ currentLetter.author }}</text>
                            <text class="letter-date">{{ currentLetter.date }}</text>
                        </view>
                        <view class="letter-body">
                            <text class="letter-text">{{ currentLetter.content }}</text>
                        </view>
                        <view class="letter-footer">
                            <text class="footer-text">—— 一份来自远方的美好 ——</text>
                        </view>
                    </view>
                </view>
                
                <view class="modal-footer">
                    <view class="modal-button confirm-button full-width" @click="closeReadModal">
                        <text class="button-text">知道了</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            loading: true,
            mediaList: [],
            navTitle: '媒体详情',
            treeInfo: null,
            treeId: null, // 添加treeId参数
            // 弹框相关状态
            showWriteModal: false,
            showReadModal: false,
            writeContent: '',
            letterList: [
                {
                    id: 1,
                    content: '今天天气非常好，适合出游。在这里留下美好的回忆，希望下一个看到的人也能感受到这份美好。',
                    author: '匿名用户',
                    date: '2024-01-15'
                },
                {
                    id: 2,
                    content: '旅行的意义不在于目的地，而在于沿途的风景和看风景的心情。愿每个来到这里的人都能找到属于自己的快乐。',
                    author: '旅行者',
                    date: '2024-01-10'
                },
                {
                    id: 3,
                    content: '这里的风景真的太美了，让人心想神怡。感谢这次旅行，让我重新找到了内心的平静。',
                    author: '山水之间',
                    date: '2024-01-08'
                }
            ],
            currentLetter: null
        }
    },
    
    computed: {
        // 获取第一个媒体项（如果第一个是视频则使用第二个）
        firstMedia() {
            if (this.mediaList.length === 0) {
                return null;
            }
            
            // 如果第一个是视频且有第二个媒体，则使用第二个
            if (this.mediaList[0].type === 'video' && this.mediaList.length > 1) {
                return this.mediaList[1];
            }
            
            // 否则使用第一个
            return this.mediaList[0];
        },
        
        // 获取实际显示的媒体索引
        displayMediaIndex() {
            if (this.mediaList.length === 0) {
                return -1;
            }
            
            // 如果第一个是视频且有第二个媒体，返回索引 1
            if (this.mediaList[0].type === 'video' && this.mediaList.length > 1) {
                return 1;
            }
            
            // 否则返回索引 0
            return 0;
        }
    },
    
    async onLoad(options) {
        // 接收传递过来的参数
        if (options.mediaData) {
            try {
                this.mediaList = JSON.parse(decodeURIComponent(options.mediaData));
            } catch (e) {
                console.error('解析媒体数据失败:', e);
                this.mediaList = [];
            }
        }
        
        if (options.title) {
            this.navTitle = decodeURIComponent(options.title);
        }
        
        if (options.treeId) {
            this.treeId = options.treeId;
        }
        
        this.loading = false;
    },
    
    methods: {
        // 预览第一个媒体
        previewFirstMedia() {
            if (this.firstMedia && this.displayMediaIndex >= 0) {
                this.previewMedia(this.displayMediaIndex);
            }
        },
        
        // 播放第一个视频
        playFirstVideo() {
            if (this.firstMedia && this.firstMedia.type === 'video') {
                console.log('播放视频:', this.firstMedia.url);
                // 这里可以添加视频播放逻辑
            }
        },
        
        // 左侧按钮点击事件 - 写一封
        onLeftButtonClick() {
            this.showWriteModal = true;
            this.writeContent = '';
        },
        
        // 右侧按钮点击事件 - 捡一封
        onRightButtonClick() {
            this.getRandomLetter();
        },
        
        // 获取随机信件
        getRandomLetter() {
            if (!this.treeId) {
                uni.showToast({
                    title: '缺少必要参数',
                    icon: 'none'
                });
                return;
            }
            
            this.$http.to_http('system/userLetters/letter/random', { treeId: this.treeId }, 'GET', '加载中').then(res => {
                res = res.data;
                if (res.code === 200) {
                    if (res.data) {
                        this.currentLetter = {
                            content: res.data.content,
                            author: res.data.author || '匿名用户',
                            date: res.data.createTime ? res.data.createTime.split(' ')[0] : new Date().toISOString().split('T')[0]
                        };
                        this.showReadModal = true;
                    } else {
                        uni.showToast({
                            title: '暂无可捡取的信件',
                            icon: 'none'
                        });
                    }
                } else {
                    uni.showToast({
                        title: res.msg || '获取信件失败',
                        icon: 'none'
                    });
                }
            }).catch(err => {
                console.error('获取随机信件失败:', err);
                uni.showToast({
                    title: '网络错误，请稍后重试',
                    icon: 'none'
                });
            });
        },
        
        // 提交书信
        submitLetter() {
            if (!this.writeContent.trim()) {
                uni.showToast({
                    title: '请输入书信内容',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.treeId) {
                uni.showToast({
                    title: '缺少必要参数',
                    icon: 'none'
                });
                return;
            }
            
            const letterData = {
                treeId: this.treeId,
                content: this.writeContent.trim()
            };
            
            this.$http.to_http('system/letters', letterData, 'POST', '投递中').then(res => {
                res = res.data;
                if (res.code === 200) {
                    uni.showToast({
                        title: '书信已投递',
                        icon: 'success'
                    });
                    
                    this.showWriteModal = false;
                    this.writeContent = '';
                } else {
                    uni.showToast({
                        title: res.msg || '投递失败',
                        icon: 'none'
                    });
                }
            }).catch(err => {
                console.error('提交书信失败:', err);
                uni.showToast({
                    title: '网络错误，请稍后重试',
                    icon: 'none'
                });
            });
        },
        
        // 关闭写信模态框
        closeWriteModal() {
            this.showWriteModal = false;
            this.writeContent = '';
        },
        
        // 关闭读信模态框
        closeReadModal() {
            this.showReadModal = false;
            this.currentLetter = null;
        },
        
        // 显示所有媒体
        showAllMedia() {
            if (this.mediaList.length === 0) {
                uni.showToast({
                    title: '暂无媒体内容',
                    icon: 'none'
                });
                return;
            }
            
            // 这里可以展示所有媒体的模态框或跳转到其他页面
            uni.showActionSheet({
                itemList: this.mediaList.map((item, index) => 
                    `${item.type === 'video' ? '视频' : '图片'} ${index + 1}`
                ),
                success: (res) => {
                    this.previewMedia(res.tapIndex);
                }
            });
        },
        
        // 分享媒体
        shareMedia() {
            if (this.firstMedia) {
                uni.showShareMenu({
                    title: this.navTitle,
                    content: `分享 ${this.mediaList.length} 个媒体项`,
                    imageUrl: this.firstMedia.type === 'image' ? this.firstMedia.url : '',
                    success: () => {
                        uni.showToast({
                            title: '分享成功',
                            icon: 'success'
                        });
                    },
                    fail: () => {
                        uni.showToast({
                            title: '分享失败',
                            icon: 'none'
                        });
                    }
                });
            } else {
                uni.showToast({
                    title: '暂无可分享的内容',
                    icon: 'none'
                });
            }
        },
        // 预览媒体内容
        previewMedia(index) {
            const currentItem = this.mediaList[index];
            
            if (currentItem.type === 'image') {
                // 预览图片
                const imageUrls = this.mediaList
                    .filter(item => item.type === 'image')
                    .map(item => item.url);
                
                const currentImageIndex = imageUrls.indexOf(currentItem.url);
                
                uni.previewImage({
                    current: currentImageIndex,
                    urls: imageUrls,
                    success: () => {
                        console.log('图片预览成功');
                    },
                    fail: (err) => {
                        console.error('图片预览失败:', err);
                        uni.showToast({
                            title: '图片预览失败',
                            icon: 'none'
                        });
                    }
                });
            } else if (currentItem.type === 'video') {
                // 跳转到视频播放页面或在当前页面播放
                this.playVideo(currentItem, index);
            }
        },
        
        // 播放视频
        playVideo(videoItem, index) {
            // 简单的视频播放处理
            uni.showModal({
                title: '视频播放',
                content: '是否要播放这个视频？',
                success: (res) => {
                    if (res.confirm) {
                        // 这里可以跳转到专门的视频播放页面
                        // 或者在当前页面打开视频播放
                        console.log('播放视频:', videoItem.url);
                        
                        // 简单实现：显示Toast提示
                        uni.showToast({
                            title: `正在播放第${index + 1}个视频`,
                            icon: 'none'
                        });
                    }
                }
            });
        },
        
        // 返回上一页
        goBack() {
            uni.navigateBack();
        }
    }
}
</script>

<style lang="scss" scoped>
.media-detail-page {
    min-height: 100vh;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
}

.u-nav-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.1);
}

.main-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 100rpx); /* 减去导航栏高度 */
}

/* 上半部分样式 */
.top-section {
    flex: 1;
    background: #fff;
    overflow: hidden;
}

.first-media-container {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.first-media-image,
.first-media-video {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.first-video-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
}

.no-media-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
}

.placeholder-text {
    color: #999;
    font-size: 28rpx;
    margin-top: 20rpx;
}

.video-play-overlay {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 2;
    cursor: pointer;
}

.media-info-badge {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
    background-color: rgba(0, 0, 0, 0.6);
    border-radius: 30rpx;
    padding: 12rpx 20rpx;
    display: flex;
    align-items: center;
    gap: 8rpx;
    z-index: 3;
}

.media-count-text {
    color: #fff;
    font-size: 24rpx;
    font-weight: 600;
}

/* 下半部分样式 */
.bottom-section {
    flex: 1;
    overflow: hidden;
}

.background-container {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.background-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.content-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    padding: 0 64rpx 20rpx 60rpx;
    gap: 88rpx;
}

.action-button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 210rpx;
    height: 210rpx;
    background: rgba(255, 255, 255, 0.15);
    border: none;
    border-radius: 20rpx;
    backdrop-filter: blur(10rpx);
    transition: all 0.3s ease;
    cursor: pointer;
}

.action-button:active {
    transform: scale(0.95);
    background: rgba(255, 255, 255, 0.25);
}

.left-button {
     background-image: url('http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/2bbbc053-f991-4e47-9743-e7a4e1e53c75.jpg?Expires=4911628387&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=%2BH%2F2AKSKdF4%2FK55qTqua5IcG1oc%3D');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.right-button {
     background-image: url('http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/331d86f2-c185-4068-b9bb-690682183f5e.jpg?Expires=4911628409&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=oX4h6ts7OsRT5AKP1tI5y15sbmE%3D');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.empty-state {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
    .content-overlay {
        padding: 0 40rpx;
    }
    
    .action-button {
        width: 140rpx;
        height: 140rpx;
    }
}

/* 动画效果 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20rpx);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.main-content {
    animation: fadeIn 0.3s ease-out;
}

/* 原生模态框样式 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    padding: 40rpx;
    box-sizing: border-box;
}

.modal-container {
    background-color: #fff;
    border-radius: 16rpx;
    width: 100%;
    max-width: 600rpx;
    max-height: 80vh;
    overflow: hidden;
    animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: scale(0.9) translateY(-50rpx);
    }
    to {
        opacity: 1;
        transform: scale(1) translateY(0);
    }
}

.modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 2rpx solid #f0f0f0;
}

.modal-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}

.modal-close {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background-color 0.3s ease;
}

.modal-close:active {
    background-color: #f5f5f5;
}

.modal-content {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;
}

.modal-footer {
    display: flex;
    padding: 30rpx;
    gap: 20rpx;
    border-top: 2rpx solid #f0f0f0;
}

.modal-button {
    flex: 1;
    height: 80rpx;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.modal-button:active {
    transform: scale(0.95);
}

.cancel-button {
    background-color: #f5f5f5;
    border: 2rpx solid #e5e5e5;
}

.cancel-button .button-text {
    color: #666;
}

.confirm-button {
    background-color: #25772f;
    border: 2rpx solid #25772f;
}

.confirm-button .button-text {
    color: #fff;
}

.full-width {
    flex: none;
    width: 100%;
}

.button-text {
    font-size: 28rpx;
    font-weight: 500;
}

/* 写信内容样式 */
.write-letter-content {
    width: 100%;
}

.letter-tips {
    margin-bottom: 20rpx;
    text-align: center;
}

.tips-text {
    color: #666;
    font-size: 24rpx;
    line-height: 1.5;
}

.letter-textarea {
    width: 100%;
    min-height: 300rpx;
    padding: 20rpx;
    border: 2rpx solid #e5e5e5;
    border-radius: 12rpx;
    font-size: 28rpx;
    line-height: 1.6;
    background-color: #fafafa;
    box-sizing: border-box;
    resize: none;
}

.letter-textarea:focus {
    border-color: #25772f;
    background-color: #fff;
}

.word-count {
    text-align: right;
    margin-top: 10rpx;
}

.count-text {
    color: #999;
    font-size: 24rpx;
}

/* 读信内容样式 */
.read-letter-content {
    width: 100%;
}

.letter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    padding-bottom: 20rpx;
    border-bottom: 2rpx solid #f0f0f0;
}

.letter-author {
    color: #25772f;
    font-size: 26rpx;
    font-weight: 600;
}

.letter-date {
    color: #999;
    font-size: 24rpx;
}

.letter-body {
    margin: 30rpx 0;
    min-height: 200rpx;
}

.letter-text {
    color: #333;
    font-size: 28rpx;
    line-height: 1.8;
    text-align: justify;
    display: block;
    word-wrap: break-word;
}

.letter-footer {
    text-align: center;
    margin-top: 30rpx;
    padding-top: 20rpx;
    border-top: 2rpx solid #f0f0f0;
}

.footer-text {
    color: #999;
    font-size: 24rpx;
    font-style: italic;
}
</style>